﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

// 计时器管理器(封装Timer，管理Timer)
public class TimerMgr : Singleton<TimerMgr>
{
    // 定时器的驱动
    private Action TimerFixedLoop;

    public TimerMgr()
    {
        GameMgr.Instance.FixedUpdateCallback += FixedLoop;
    }

    // 创建一个定时器
    public Timer CreateTimer(float duringTime, int repeatTimes, Action callback)
    {
        var timer = new Timer();
        timer.DuringTime = duringTime;
        timer.RepeatTimes = repeatTimes;
        timer.Callback = callback;

        return timer;
    }

    public void FixedLoop()
    {
        if (TimerFixedLoop != null) { TimerFixedLoop(); }
    }

    // 定时器
    public class Timer
    {
        public float StartTime;
        public string Name;
        // 定时周期
        public float DuringTime;
        // 重复次数 // 小于零，表示无限循环
        public int RepeatTimes;
        // 输出闹铃
        public Action Callback;

        // 计时开始时间

        private float _passedTime;
        // 已经重复了多少次
        private int _repeatedTimes;
        // 开始计时
        public void Start()
        {
            _passedTime = 0;
            _repeatedTimes = 0;
            TimerMgr.Instance.TimerFixedLoop += FixedLoop;
        }

        // 当前周期内的剩余时间
        public float LeftTimeInCurCycle { get { return DuringTime - _passedTime; } }

        // 停止计时
        public void Stop()
        {
            TimerMgr.Instance.TimerFixedLoop -= FixedLoop;
        }

        // 此函数被定时循环调用
        public void FixedLoop()
        {
            //_passedTime += Time.fixedDeltaTime;
            _passedTime += Time.deltaTime;
            if (_passedTime > DuringTime)
            {
                // 叮铃铃一下
                _passedTime -= DuringTime;
                _repeatedTimes++;

                if (Callback != null) { Callback(); }

                // 记录重复次数
                if ((RepeatTimes >= 0)
                    && (_repeatedTimes >= RepeatTimes))
                {
                    Stop();
                    return;
                }
            }
        }
    }
}

